<?php

namespace App\Admin\Controllers;

use App\Models\Engineering;
use App\Models\AdminUser;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class EngineeringController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Engineering(), function (Grid $grid) {
            $grid->disableViewButton();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->like('engineering_name','工程名称')->width(5);


                $filter->like('manager','管理人员')->select(function (){
                    $result = AdminUser::where('name','<>','Administrator')->get(['id','name']);
                    $list = array();
                    foreach ($result as $info){
                        $role_id = DB::table('admin_role_users')->where('user_id',$info->id)->value('role_id');
                        $role_name = DB::table('admin_roles')->where('id',$role_id)->value('name');
                        $list[$info['id']] = $info['name'].'--'.$role_name;
                    }
                    return $list;
                })->width(5);

            });

            $grid->number('序号');

            $grid->column('status','状态')->display(function ($status) {
                if($status == 1){
                    return "<span style='color:blue'>正常</span>";
                }else{
                    return "<span style='color:red'>结项</span>";
                }
            });

            $grid->column('province_name','省');
            $grid->column('city_name','市');
            $grid->column('district_name','区');

            $grid->column('engineering_name')->limit(10);
            $grid->column('manager','管理人员')->display(function ($manager) {
                if($manager != null){
                    $result = DB::table('admin_users')->whereIn('id',json_decode($manager))->get(['id','name']);
                    $list = array();
                    foreach ($result as $info){
                        $role_id = DB::table('admin_role_users')->where('user_id',$info->id)->value('role_id');
                        $role_name = DB::table('admin_roles')->where('id',$role_id)->value('name');
                        $list[$info->id] = $info->name.'--'.$role_name;
                    }
                    return $list;
                }
            })->label();


            $grid->column('enter','本月是否有新增人员')->display(function () {
                $now = Carbon::now();
                $twelveMonthsAgo = $now->firstOfMonth();

                $start = $twelveMonthsAgo->toDateTimeString();
                $end = Carbon::now()->format('Y-m-d');

                $res = DB::table('work_user')->where('engineering',$this->engineering_name)->where('status',1)->where('deleted_at',null)->whereBetween('enter_time',[$start,$end])->count();
                if($res > 0){
                    return "<span style='color:blue'>有新增</span>";
                }else{
                    return "<span style='color:red'>没有新增</span>";
                }

            });
            $grid->column('exit','本月是否有离职人员')->display(function () {
                $now = Carbon::now();
                $twelveMonthsAgo = $now->firstOfMonth();

                $start = $twelveMonthsAgo->toDateTimeString();
                $end = Carbon::now()->format('Y-m-d');

                $res = DB::table('work_user')->where('engineering',$this->engineering_name)->where('status',2)->where('deleted_at',null)->whereBetween('exit_time',[$start,$end])->count();
                if($res > 0){
                    return "<span style='color:blue'>有新增</span>";
                }else{
                    return "<span style='color:red'>没有新增</span>";
                }
            });

//            $grid->column('created_at');
//            $grid->column('updated_at')->sortable();

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Engineering(), function (Show $show) {
            $show->field('id');
            $show->field('engineering_name');
            $show->field('manager');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Engineering(), function (Form $form) {
            $form->display('id');
            $form->distpicker(['province_name', 'city_name', 'district_name']);

            $form->text('engineering_name');

            $form->multipleSelect('manager',__('管理人员'))->options(
                function (){
//                    $result = AdminUser::where('name','<>','Administrator')->get(['id','name']);
                    $result = AdminUser::get(['id','name']);
                    $list = array();
                    foreach ($result as $info){
                        $role_id = DB::table('admin_role_users')->where('user_id',$info->id)->value('role_id');
                        $role_name = DB::table('admin_roles')->where('id',$role_id)->value('name');
                        $list[$info['id']] = $info['name'].'--'.$role_name;
                    }
                    return $list;
                }
            )->saving(function ($value) {
                // 转化成json字符串保存到数据库
                return json_encode($value);
            });

//            $form->radio('status','状态')->options(['1' => '正常', '2'=> '结项'])->default('1');



            $form->radio('status','状态')
                ->when([2], function (Form $form) {
                    // 值为1和4时显示文本框
                    $form->text('queren','确认结项');
                })
                ->options([
                    1 => '正常',
                    2 => '结项'
                ])
                ->default(1);



            $form->display('created_at');
            $form->display('updated_at');


            $form->saving(function (Form $form) {
                if ($form->isCreating()) {
                    $cf = DB::table('engineering')->where('engineering_name',$form->engineering_name)->where('deleted_at',null)->first();
                    if(!empty($cf)){
                        return $form->response()->error('该工程已经存在');
                    }
                }

                if($form->status == 1 && $form->queren != ''){
                    return $form->response()->error('存在确认信息，请清除');
                }

                if($form->status == 2 && $form->queren != '确认结项'){
                    return $form->response()->error('确认失败，请重新输入汉字“确认结项”');
                }

                if (!$form->isCreating() && $form->status == 2 && $form->queren == '确认结项') {
                    $project_closure = DB::table('work_user')->where('misdeed',1)->where('deleted_at',null)->where('engineering',$form->engineering_name)->get()->map(function ($value) {return (array)$value;})->toArray();
                    DB::table('work_user')->where('misdeed',1)->where('engineering',$form->engineering_name)->update(['deleted_at'=>Carbon::now()]);
                    DB::table('project_closure_user')->insert($project_closure);

                    foreach ($project_closure as $key => $value){
                        $history = [];
                        $history['name'] = $value['name'];
                        $history['id_card'] = $value['id_card'];
                        $history['engineering'] = $value['engineering'];
                        $history['type'] = 5;
                        $history['details'] = '结项';
                        $history['enter_time'] = $value['enter_time'];
                        $history['created_at'] = Carbon::now();
                        DB::table('work_user_history')->insert($history);
                    }

                }

            });


        });
    }



//    public function admin_user(Request $request)
//    {
//        $q = $request->get('q');
//        if($q==''){
//             return AdminUser::where('name','<>','Administrator')->paginate(null, ['id', 'name as text']);
//        }
//        return AdminUser::where('name', 'like', "%$q%")->paginate(null, ['id', 'name as text']);
//    }
}
